<?php
/**
 * Created by PhpStorm.
 * User: zhang
 * Date: 2018/9/16
 * Time: 0:55
 */

namespace app\teacher\controller;

use app\common\model\TeacherBase;
use app\student\model\StudentManager;
use app\teacher\model\ExcelReader;
use app\teacher\model\TeacherExamManager;

class Student extends TeacherBase{

    const MISS_PARAM = "请输入参数";
    const ERROR_FORMAT = "上传格式不对";

    private $studentManager;
    private $teacherExamManager;

    private $student_array=array("A"=>"考号","B"=>"姓名","C"=>"学院","D"=>"系","E"=>"班级","F"=>"学号","G"=>"场次");
    private $student_score=array("A"=>"场次","B"=>"姓名","C"=>"学号","D"=>"成绩");

    public function __construct()
    {
        parent::__construct();
        $this->studentManager = new StudentManager();
        $this->teacherExamManager = new TeacherExamManager();
    }

    /**
     *
     * @api {post} /teacher/student/ 提交学生名单
     * @apiDescription 提交学生名单
     * @apiGroup teacher
     *
     * @apiParam {Object} file student.xlsx or student.xls
     *
     *
     * @apiSuccess {String} code 0 表示失败 1 表示成功.
     * @apiSuccess {String} msg 返回提交失败人员名单.
     * @apiSuccessExample {json} Success-Response:
     *     {
     *       "code": "1",
     *       "msg": [{"返回报名场次"}]
     *     }
     */
    public function index(){
        $tmp_file = $_FILES ['file'] ['tmp_name']; //临时文件

        move_uploaded_file($_FILES["file"]["tmp_name"],
            "upload/student.xls");

        $inputFileName = "upload/student.xls";//$result = \PHPExcel_IOFactory::load("upload/" . $_FILES["file"]["name"]);

//        if(!($_FILES["file"]["name"] == "student.xlsx" || $_FILES["file"]["name"] == "student.xls")){
//            echoJson(0, "请正确上传excel");
//        }
        $count = 0;

        $inputFileType = \PHPExcel_IOFactory::identify($inputFileName);
        $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);

        $chunkSize = 20;	// 定义每块读去的行数

        $PHPExcel = $objReader->load($inputFileName);        //
        $currentSheet = $PHPExcel->getSheet(0);
        $allColumn = $currentSheet->getHighestColumn();   //**取得最大的列号*/
        $allRow = $currentSheet->getHighestRow();        //**取得一共有多少行*/

        $list = 1;

        for($colIndex='A';$colIndex<='G';$colIndex++){
            $addr = $colIndex."1";
            $cell = $currentSheet->getCell($addr)->getValue();
            if($cell instanceof PHPExcel_RichText){ //富文本转换字符串
                $cell = $cell->__toString();
            }
            //print_r($cell);

            if($this->student_array[$colIndex] != $cell){
                echoJson(0, self::ERROR_FORMAT);
            }
        }

        for($rowIndex=2;$rowIndex<=$allRow;$rowIndex++){
            //循环读取每个单元格的内容。注意行从1开始，列从A开始
            $list = 1;
            for($colIndex='A';$colIndex<=$allColumn;$colIndex++){
                $addr = $colIndex.$rowIndex;
                $cell = $currentSheet->getCell($addr)->getValue();
                if($cell instanceof PHPExcel_RichText){ //富文本转换字符串
                    $cell = $cell->__toString();
                }
                //print_r($cell);
                //$data[$arr[$list++]] = $cell;
                switch ($colIndex){
                    case 'B': $data["name"] = $cell;break;
                    case 'C': $data["college"] = $cell;break;
                    case 'E': $data["class"] = $cell;break;
                    case 'F': $data["id"] = $cell;break;
                    default:break;
                }
            }

            //var_dump(json_encode($data));
            if(!$this->studentManager->insertStudent($data)){
                $person[$rowIndex] = $data;
            }else{
                $count++;
            }
        }

        //if(count($person) == 0)
            echoJson(1, "成功添加".$count."名学生");
        //else
        //    echoJson(0, $person);
    }

    /**
     *
     * @api {post} /teacher/student/score 提交考场成绩
     * @apiDescription 提交考场成绩
     * @apiGroup teacher
     *
     * @apiParam {object} file score.xls or score.xlsx
     *
     *
     * @apiSuccess {String} code 0 表示失败 1 表示成功.
     * @apiSuccess {String} msg 返回报名场次.
     * @apiSuccessExample {json} Success-Response:
     *     {
     *       "code": "1",
     *       "msg": [{"返回报名场次"}]
     *     }
     */
    public function score(){

        $tmp_file = $_FILES ['file'] ['tmp_name']; //临时文件

        move_uploaded_file($_FILES["file"]["tmp_name"],
            "upload/score.xls");

        $inputFileName = "upload/score.xls";//$result = \PHPExcel_IOFactory::load("upload/" . $_FILES["file"]["name"]);

//        if(!($_FILES["file"]["name"] == "score.xlsx" || $_FILES["file"]["name"] == "score.xls")){
//            echoJson(0, "请正确上传excel");
//        }

        $inputFileType = \PHPExcel_IOFactory::identify($inputFileName);
        $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);
        //var_dump($objPHPExcel->getSheetCount());		// 获取工作表的个数

        //       $objReader->setLoadSheetsOnly("student");
        //       $excelReader = new ExcelReader();
//        $filterSubset = new MyReadFilter();
//        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
//        $objReader->setReadFilter($filterSubset);		// 设置实例化的过滤器对象
//        $objPHPExcel = $objReader->load($inputFileName);
        $chunkSize = 20;	// 定义每块读去的行数

        $PHPExcel = $objReader->load($inputFileName);        //
        $currentSheet = $PHPExcel->getSheet(0);
        $allColumn = $currentSheet->getHighestColumn();   //**取得最大的列号*/
        $allRow = $currentSheet->getHighestRow();        //**取得一共有多少行*/

//        var_dump($allColumn);
//        var_dump($allRow);
        $list = 1;
        for($colIndex='A';$colIndex<=$allColumn;$colIndex++){
            $addr = $colIndex."1";
            $cell = $currentSheet->getCell($addr)->getValue();
            if($cell instanceof PHPExcel_RichText){ //富文本转换字符串
                $cell = $cell->__toString();
            }
            //print_r($cell);

            if($this->student_score[$colIndex] != $cell){
                echoJson(0, self::ERROR_FORMAT);
            }
        }

        //$data["status"]=0;
        for($rowIndex=2;$rowIndex<=$allRow;$rowIndex++){
            //循环读取每个单元格的内容。注意行从1开始，列从A开始
            $list = 1;
            for($colIndex='A';$colIndex<=$allColumn;$colIndex++){
                $addr = $colIndex.$rowIndex;
                $cell = $currentSheet->getCell($addr)->getValue();
                if($cell instanceof PHPExcel_RichText){ //富文本转换字符串
                    $cell = $cell->__toString();
                }
                //print_r($cell);
                switch ($colIndex){
                    case 'A': $data["exam_id"] = $cell;break;
                    //case 'B': $data["college"] = $cell;break;
                    case 'C': $data["student_id"] = $cell;break;
                    case 'D': $data["score"] = $cell;break;
                    default:break;
                }
            }
            $data["status"] = 0;
            if(!$this->teacherExamManager->updateStudentScore($data)){
                $person[$rowIndex] = $data;
            }
        }

        if(count($person) == 0)
            echoJson(1, "成功添加".($allRow-1)."名学生成绩");
        else
            echoJson(0, $person);
    }

    /**
     *
     * @api {get} /teacher/student/cls 查询学生名单
     * @apiDescription 查询学生名单
     * @apiGroup teacher
     *
     * @apiParam {object} class 班级
     *
     *
     * @apiSuccess {String} code 0 表示失败 1 表示成功.
     * @apiSuccess {String} msg 返回报名场次.
     * @apiSuccessExample {json} Success-Response:
     *     {
     *       "code": "1",
     *       "msg": [{"返回报名场次"}]
     *     }
     */
    public function cls(){
        $class = $_GET["class"];

        if(!isset($class)){
            echoJson(1, self::MISS_PARAM);
        }

        echoJson(1, $this->studentManager->getStudentAllByClass($class));
    }
}